local key_board = GetModConfigData("sw_mainboard")
if not key_board then return end

local TEMPLATES = require "widgets/redux/templates"
local Mainboard = require "widgets/huxi_window"
local TextBtn = require "widgets/textbutton"
local ImageButton = require "widgets/imagebutton"

local POSDATA = "Pos"		-- 存储四个数据 位置(X,Y), 贴图(altas,tex)
local TEXDATA = "Tex"
local SaveSHide = "butterfly"
local SHide = false

local S_KEY = "LICON_SEARCH_KEY"

local function ViewLicon()
	if InGame() and GLOBAL.ThePlayer.HUD.controls and GLOBAL.ThePlayer.HUD.controls.lIcon then
		if SHide then
			GLOBAL.ThePlayer.HUD.controls.lIcon:Hide()
		else
			GLOBAL.ThePlayer.HUD.controls.lIcon:Show()
		end
	end
end
local writeablescreen
local WriteableWidget = require "screens/TMIP_writeablewidget"
local writeable_widget_args = {
    animbank = "ui_board_5x3",
    animbuild = "ui_board_5x3",
    menuoffset = GLOBAL.Vector3(6, -70, 0),
    cancelbtn = {
        text = GLOBAL.STRINGS.UI.TRADESCREEN.CANCEL,
        cb = function()
            GLOBAL.ChatHistory:AddToHistory(GLOBAL.ChatTypes.Message, nil, nil, "中键查找", "取消", COLORS.WHITE)
        end,
        control = GLOBAL.CONTROL_CANCEL
    },
    acceptbtn = {
        text = GLOBAL.STRINGS.UI.TRADESCREEN.ACCEPT,
        cb = function(w, meta)
            SaveModData(S_KEY, w:GetText())
            GLOBAL.ChatHistory:AddToHistory(GLOBAL.ChatTypes.Message, nil, nil, "中键查找", "已存储", COLORS.WHITE)
        end,
        control = GLOBAL.CONTROL_ACCEPT
    }
}
local function OpenWriteScreen(meta)
    if writeablescreen then
        writeablescreen:KillAllChildren()
        writeablescreen:Kill()
        writeablescreen = nil
    end
    writeablescreen = WriteableWidget(writeable_widget_args, meta)
    GLOBAL.ThePlayer.HUD:OpenScreenUnderPause(writeablescreen)
    if GLOBAL.TheFrontEnd:GetActiveScreen() == writeablescreen then
        writeablescreen.edit_text:SetEditing(true)
    end
end

DEAR_BTNS:AddDearBtn("modicon.xml", "modicon.tex", "蓝蝴蝶", "重置图标 (按住alt点击禁用图标)", true, function()
	if InGame() and GLOBAL.ThePlayer.HUD.controls and GLOBAL.ThePlayer.HUD.controls.lIcon then
		local img = GLOBAL.ThePlayer.HUD.controls.lIcon
		local screen_w, screen_h = GLOBAL.TheSim:GetScreenSize()
		local D_x,D_y,D_altas,D_tex= screen_w*1750/1920,screen_h*50/1080,"modicon.xml","modicon.tex"
		img:SetVAnchor(GLOBAL.ANCHOR_BOTTOM)    --设置原点到屏幕下方
		img:SetHAnchor(GLOBAL.ANCHOR_LEFT)        --设置原点到屏幕左方，综合起来就是左下方
		img:SetPosition(D_x, D_y)
		img:SetTextures(D_altas, D_tex)
		local sizeX, sizeY = img:GetSize()
		local trans_scale = math.min(100 / sizeX, 100 / sizeY)
		img:SetNormalScale(trans_scale)
		img:SetFocusScale(trans_scale * 1.2)
		SaveModData(TEXDATA, {
            altas = D_altas,
            tex = D_tex,
        })
		SaveModData(POSDATA, {
            posX = D_x,
            posY = D_y,
        })

		if GLOBAL.TheInput:IsKeyDown(GLOBAL.KEY_LALT) then
			SHide = true
			TIP("提示", "red", "你已经隐藏了面板的图标, 现在只能通过按键呼出面板", "chat")
			ViewLicon()
			SaveModData(SaveSHide, SHide)
		else
			SHide = false
			ViewLicon()
			SaveModData(SaveSHide, SHide)
		end
	end
end)

AddClassPostConstruct("widgets/controls", function(self)
	local function ToggleShowBoard()
		if InGame() and self.mainboard then
			if self.mainboard:IsVisible() then
				self.mainboard:CloseIt()
			else
				self.mainboard:ShowIt()
			end 
		end
	end
	-- 按钮
	local texdata = LoadModData(TEXDATA)
	local posdata = LoadModData(POSDATA)
	SHide = LoadModData(SaveSHide)
	local length_img = 70
	local tex = texdata and texdata.tex or "modicon.tex"
	local altas = texdata and texdata.altas or "modicon.xml"
	local screen_w, screen_h = GLOBAL.TheSim:GetScreenSize()
	local D_x,D_y= screen_w*1750/1920,screen_h*50/1080
	local posX = posdata and posdata.posX or D_x
	local posY = posdata and posdata.posY or D_y
	-- 随机图标
	local function SetFixedImg(img, length_img, tex, altas)
		if not altas then
			altas = GLOBAL.GetInventoryItemAtlas(tex)
		end
		if not altas or not GLOBAL.TheSim:AtlasContains(altas, tex) then
			altas,tex = "modicon.xml", "modicon.tex"
		end
		img:SetTextures(altas, tex)

		local sizeX, sizeY = img:GetSize()
		local trans_scale = math.min(length_img / sizeX, length_img / sizeY)
		img:SetNormalScale(trans_scale)
		img:SetFocusScale(trans_scale * 1.2)
		
		SaveModData(TEXDATA, {
			altas = altas,
			tex = tex,
		})
	end
	local function GetRandomImg()
		if GLOBAL.PREFAB_SKINS then
			local filters = GLOBAL.GetRandomItem(GLOBAL.PREFAB_SKINS)
			if type(filters) == "table" then
				local tex = GLOBAL.GetRandomItem(filters)
				if type(tex) == "string" then
					tex = tex..".tex"
					local atlas = GLOBAL.GetInventoryItemAtlas(tex)
					return atlas and tex
				end
			end
		end
	end
	local function SetRandomImg(img, oldtex)
		local flag = true
		local newtex
		while flag do
			newtex = GetRandomImg()
			if newtex and newtex ~= oldtex then
				flag = false
			end
		end
		SetFixedImg(img, length_img, newtex)
	end
	local function GetPosStr()
		local x, _, z = GLOBAL.ThePlayer.Transform:GetWorldPosition()
		return "我的坐标: ("..string.format("%.2f", x).." , "..string.format("%.2f",z)..")"
	end

	-- mainboard
    self.mainboard = self:AddChild(Mainboard(DEAR_BTNS:GetBtns()))
	local img = self:AddChild(ImageButton())
	SetFixedImg(img, length_img, tex, altas)
	self.lIcon = img
	self.lIcon:SetVAnchor(GLOBAL.ANCHOR_BOTTOM)    --设置原点到屏幕下方
	self.lIcon:SetHAnchor(GLOBAL.ANCHOR_LEFT)        --设置原点到屏幕左方，综合起来就是左下方
	self.lIcon:SetPosition(posX, posY)
	-- 这是种糟糕的写法，暂时没啥好的写法，鸽了
	-- self.lIcon:SetTooltip(GLOBAL.STRINGS.RMB.."刷新\n"..GLOBAL.TheInput:GetLocalizedControl(GLOBAL.TheInput:GetControllerID(), 61).."拖拽")
	self.lIcon:SetTooltip(GLOBAL.STRINGS.LMB.."拖拽".."  "..GLOBAL.STRINGS.RMB.."换肤\n")
	-- 鼠标跟随
	local lasttime = 0
	self.lIcon.FollowMouse = function(self)
		if self.followhandler == nil then
			self.followhandler = GLOBAL.TheInput:AddMoveHandler(function(x, y)
				self:UpdatePosition(x, y)
			end)
		end
	end
	self.lIcon.OnMouseButton = function(_self, button, down, x, y)    --注意:此处应将self.drag_button替换为你要拖拽的widget
		if button == GLOBAL.MOUSEBUTTON_LEFT and down and not GLOBAL.TheInput:IsControlPressed(GLOBAL.CONTROL_FORCE_INSPECT) then    --鼠标中键按下
			lasttime = GLOBAL.GetTime()
			return _self:FollowMouse()
		elseif button == GLOBAL.MOUSEBUTTON_LEFT and not down and not GLOBAL.TheInput:IsControlPressed(GLOBAL.CONTROL_FORCE_INSPECT) then            --鼠标中键抬起
			if GLOBAL.GetTime()-lasttime < 0.3 then
				if not GLOBAL.TheInput:IsControlPressed(GLOBAL.CONTROL_FORCE_INSPECT) then
					ToggleShowBoard()
				end
			else
				SaveModData(POSDATA, {
					posX = x,
					posY = y,
				})
			end
		elseif down and GLOBAL.TheInput:IsControlPressed(GLOBAL.CONTROL_FORCE_INSPECT) and GLOBAL.ThePlayer.HUD._StatusAnnouncer then
			if button == GLOBAL.MOUSEBUTTON_LEFT then
				GLOBAL.ThePlayer.HUD._StatusAnnouncer:Announce(os.date("今天是 %Y年%m月%d日, 当前时间 %H:%M:%S ") )
			elseif button == GLOBAL.MOUSEBUTTON_RIGHT then 
				GLOBAL.ThePlayer.HUD._StatusAnnouncer:Announce(GetPosStr())
			end
		elseif button == GLOBAL.MOUSEBUTTON_MIDDLE and not down then
			if GLOBAL.MOD_ShroomCake and GLOBAL.MOD_ShroomCake.SearchPrefabWithClick and GLOBAL.STRINGS and GLOBAL.STRINGS.NAMES then
				local cursor = GetActiveItem()
				if cursor and cursor.prefab and type(cursor.name)=="string" then
					print(cursor.prefab)
					TIP("中键查找", "pink", "鼠标物品:"..cursor.name, "chat")
					GLOBAL.MOD_ShroomCake.SearchPrefabWithClick(cursor.prefab, true)
				else	
				local search_str = LoadModData(S_KEY)
				if type(search_str) ~= "string" or GLOBAL.TheInput:IsKeyDown(GLOBAL.KEY_LALT) then
					TIP("中键查找", "pink", "请输入查找内容，支持代码或者中文（精确匹配请在前面输入#）", "chat")
					OpenWriteScreen()
				else
					if string.sub(search_str, 1, 1) == "#" then -- 判断是否以#开头
						local search_str = string.sub(search_str, 2, string.len(search_str)) -- 提取#后面的内容
						local prefab
						for prefab_u,string_chi in pairs(GLOBAL.STRINGS.NAMES)do
							if type(prefab_u)=="string" and (string.lower(prefab_u) == search_str 
								or prefab_u == search_str
								or string_chi == search_str) then
									prefab = string.lower(prefab_u)
									break
							end
						end
						if prefab then
							GLOBAL.MOD_ShroomCake.SearchPrefabWithClick(prefab, true)
						else
							TIP("中键查找", "pink", "未能匹配任何物品, 请按ALT+中键点击图标重新输入", "chat")
						end
					else
						local pb_table = {}
						local chi_table = {}
						for prefab_u,string_chi in pairs(GLOBAL.STRINGS.NAMES)do
							if type(prefab_u) == "string" and str_contains(prefab_u, search_str) or str_contains(string_chi, search_str) then
								table.insert(pb_table,string.lower(prefab_u))
								table.insert(chi_table, string_chi)
							end
						end
						if #chi_table > 1 then
							TIP("中键查找", "pink", "查找列表:"..table.concat(chi_table, "，"), "chat")
							TIP("中键查找", "pink", "可以按ALT+中键点击图标重新输入", "chat")
						elseif #chi_table == 0 then
							TIP("中键查找", "pink", "未能匹配任何物品, 请按ALT+中键点击图标重新输入", "chat")
						end
						for _, prefab in pairs(pb_table)do
							if GLOBAL.MOD_ShroomCake.SearchPrefabWithClick(prefab, true) then
								break
							end
						end
					end
				end
				end
			end
		end
		_self:UpdatePosition(x, y)
		_self:StopFollowMouse()
	end
	img.OnControl = LROnControl
    img:SetOnClick(function(lmb)
		if not lmb then SetRandomImg(img, tex) end
	end)
	img:MoveToFront()
	if SHide then
		img:Hide()
	else
		img:Show()
	end


	AddBindBtn("sw_mainboard", ToggleShowBoard)
end)
